import express from 'express';
const commitRouter = express.Router();

/**
 * 提交文件到远程仓库.
 *
 * query参数:
 *  - commitCount: 提交次数, 默认为1次.
 */
commitRouter.get('/', async (req, res) => {
	let commitCount = Number(req.query.commitCount);
	if (isNaN(commitCount) || commitCount < 1 || commitCount > 30) commitCount = 1;

	for (let i = commitCount; i >= 1; i--) {
		try {
			await updateTargetFile(res);
		} catch (e) {
			return;
		}

		// 延时N秒后执行下一次
		await new Promise((resolve) => setTimeout(resolve, Number(process.env.COMMIT_INTERVAL_MS)));
		if (i !== 1) continue;

		// 最后一次统一提交远程.
		try {
			await git.push('origin', 'master', { '--force': null });
			return res.json(formatResJson({ msg: '任务执行成功!' }));
		} catch (e: any) {
			return res.json(formatResJson({ code: 'Fail', msg: `推送目标文件内容失败:${e?.message}}` }));
		}
	}

	// 正常情况下不会执行这里, 在此之前已经返回信息给客户端了.
	return res.json(formatResJson({ code: 'Fail', msg: '处理异常!' }));
});

module.exports = commitRouter;
